package com.zlyx.easy.mybatis.aspect;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.map.EasyMap;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.database.annotations.EasySelect;
import com.zlyx.easy.database.aspects.AbstractSelectAspect;
import com.zlyx.easy.database.local.Page;
import com.zlyx.easy.database.local.ReturnType;
import com.zlyx.easy.mybatis.annotations.EasyMapper;
import com.zlyx.easy.mybatis.mapper.MybatisMapper;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年1月14日 下午12:27:45
 */
@Aspect
@Component
public class MybatisAspect extends AbstractSelectAspect {

	@Autowired
	private MybatisMapper mybatisMapper;

	@Override
	public Object doAspect(Method method, boolean isPage, String sql, EasyMap<String, Object> paramsMap) {
		if (isPage) {
			if (method.getReturnType() == Page.class) {
				String countSql = sql.replace(sql.substring(sql.indexOf("select") + 6, sql.indexOf("from")),
						" count(*) ");
				ReturnType.clear();
				Object count = mybatisMapper.selectOne(countSql);
				if (ObjectUtils.isEmpty(count) || (Long) count == 0) {
					Logger.warn(method.getDeclaringClass(), "No results return!");
					return null;
				}
				ReturnType.setType(method);
				List<?> data = mybatisMapper.page(sql, paramsMap.getValue(EasySelect.PAGENUM),
						paramsMap.getValue(EasySelect.PAGSIZE));
				return new Page<>(data, (Long) count);
			} else {
				return mybatisMapper.page(sql, paramsMap.getValue(EasySelect.PAGENUM),
						paramsMap.getValue(EasySelect.PAGSIZE));
			}
		}
		return mybatisMapper.select(sql);
	}

	@Override
	public boolean isAspect(Method method) {
		return AnnotationUtils.findAnnotation(method.getDeclaringClass(), EasyMapper.class) != null;
	}

}
